<template>
  <div class="dashboard-container">
    <!-- <HkVideo v-bind="config" /> -->

    <!-- 侧边栏 -->
    <div class="sidebar">
      <el-form ref="formRef" :model="form">
        <el-form-item label="IP" prop="ip">
          <el-input v-model="form.ip" />
        </el-form-item>
        <el-form-item label="端口号" prop="port">
          <el-input v-model="form.port" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" />
        </el-form-item>
        <el-form-item label="通道号" prop="channelID">
          <el-input v-model="form.channelID" />
        </el-form-item>
        <el-form-item label="通道列表">
          <el-select v-model="selectedChannel">
            <el-option
              v-for="channel in channels"
              :key="channel.id"
              :label="channel.name"
              :value="channel.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="loginDevice">登录</el-button>
          <el-button @click="logout">登出</el-button>
        </el-form-item>

        <el-form-item>
          <el-button @click="onStartPlayback">开始预览</el-button>
          <el-button @click="onStopPlayback">停止预览</el-button>
        </el-form-item>
      </el-form>

      <div class="log">
        <el-input type="textarea" :rows="10" v-model="log" readonly></el-input>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="main">
      <div id="video"></div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from "vue";

const formRef = ref(null);

const form = reactive({
  ip: "172.16.0.241",
  port: 80,
  username: "admin",
  password: "Aa123456",
  channelID: 1,
});

const szDeviceIdentify = ref(null);
const log = ref("");

const initPlugin = () => {
  WebVideoCtrl.I_InitPlugin({
    bWndFull: true, // 单窗口双击全屏
    iWndowType: 1, // 分屏类型，默认值为 1，表示单画面
    bDebugMode: true, // JS 调试模式
    cbInitPluginComplete: function () {
      WebVideoCtrl.I_InsertOBJECTPlugin("video").then(
        () => {
          console.log("插件初始化成功！");
          addLog("插件初始化成功！");

          WebVideoCtrl.I_CheckPluginVersion().then((bFlag) => {
            if (bFlag) {
              alert(
                "检测到新的插件版本，双击开发包目录里的HCWebSDKPlugin.exe升级！"
              );
            } else {
            }
          });
        },
        () => {
          alert(
            "插件初始化失败，请确认是否已安装插件；如果未安装，请双击开发包目录里的HCWebSDKPlugin.exe安装！"
          );
        }
      );
    },
  });
};

const loginDevice = () => {
  WebVideoCtrl.I_Login(form.ip, 1, form.port, form.username, form.password, {
    timeout: 3000,
    success: function (xmlDoc) {
      szDeviceIdentify.value = form.ip + "_" + form.port;
      console.log("登录成功！设备标识：", szDeviceIdentify.value);
      addLog(`登录成功！设备标识：${szDeviceIdentify.value}`);

      setTimeout(() => {
        getChannelList();
      }, 1000);
    },
    error: function (error) {
      console.log("登录失败，原因：", error);
    },
  });
};

const selectedChannel = ref(null);
const channels = ref([]);

const getChannelList = () => {
  if (null == szDeviceIdentify.value) {
    return;
  }

  WebVideoCtrl.I_GetDigitalChannelInfo(szDeviceIdentify.value, {
    success: function (xmlDoc) {
      const channelNodes = xmlDoc.getElementsByTagName(
        "InputProxyChannelStatus"
      );
      const tempChannels = [];

      log.value += `可用通道数：${channelNodes.length}\n`;

      for (let i = 0; i < channelNodes.length; i++) {
        const channelNode = channelNodes[i];
        const id = channelNode.getElementsByTagName("id")[0]?.textContent;
        const name =
          channelNode.getElementsByTagName("name")[0]?.textContent ||
          `IPCamera ${i < 9 ? "0" + (i + 1) : i + 1}`;
        const online =
          channelNode.getElementsByTagName("online")[0]?.textContent;

        if (online === "false") {
          continue; // 跳过不在线的通道
        }

        tempChannels.push({ id, name });
      }

      channels.value = tempChannels; // 更新 channels 列表
    },
    error: function (error) {
      console.log("获取数字通道失败！原因：", error);
    },
  });
};

const logout = async () => {
  if (null == szDeviceIdentify.value) {
    return;
  }

  try {
    await WebVideoCtrl.I_Logout(szDeviceIdentify.value);

    console.log(`登出成功！设备标识 ${szDeviceIdentify.value}`);
    addLog(`登出成功！设备标识：${szDeviceIdentify.value}`);

    szDeviceIdentify.value = null;
  } catch (error) {
    console.log(`登出失败！原因：`, error);
  }
};

const onStartPlayback = () => {
  const oWndInfo = WebVideoCtrl.I_GetWindowStatus(0);

  if (null == szDeviceIdentify.value) {
    return;
  }

  const startPlayback = () => {
    WebVideoCtrl.I_StartRealPlay(szDeviceIdentify.value, {
      iStreamType: 1,
      iChannelID: 1,
      success: function () {
        console.log("开始预览成功");
      },
      error: function (error) {
        console.log("开始预览失败，原因：", error);
      },
    });
  };

  if (oWndInfo != null) {
    WebVideoCtrl.I_Stop({
      success: function () {
        startPlayback();
      },
    });
  } else {
    startPlayback();
  }
};

const onStopPlayback = () => {
  var oWndInfo = WebVideoCtrl.I_GetWindowStatus();

  if (oWndInfo != null) {
    WebVideoCtrl.I_Stop({
      success: function () {
        console.log("停止预览成功");
      },
      error: function (error) {},
    });
  }
};

const destroyPlugin = async () => {
  try {
    await WebVideoCtrl.I_DestroyPlugin();
    console.log(`销毁插件成功！`);
  } catch (error) {
    console.log(`销毁插件失败！`, error);
  }
};

const addLog = (content) => {
  const now = new Date();

  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，需要加1
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");

  const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;

  log.value += `${formattedTime} - ${content}\n`;
};

onMounted(() => {
  initPlugin();
});

onBeforeUnmount(async () => {
  await logout();
  await destroyPlugin();
});
</script>

<style scoped>
.dashboard-container {
  display: flex;
  width: 100%;
  height: 100%;
}

.sidebar {
  display: flex;
  flex-direction: column;
  width: 400px;
  padding: 10px;
  background-color: #f5f6fa;
}

.main {
  flex: 1;
  padding: 10px;
  background-color: #718092;
}

#video {
  width: 100%;
  height: 100%;
}

.log {
  height: auto;
}
</style>
